package com.bestcem.xm.user.grpc.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ObjectId;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.user.constant.BusinessConstant;
import com.bestcem.xm.user.entity.pojo.UserDO;
import com.bestcem.xm.user.enums.BooleanStatusEnum;
import com.bestcem.xm.user.enums.OrgInnerFlagEnum;
import com.bestcem.xm.user.enums.UserStatusEnum;
import com.bestcem.xm.user.grpc.service.converter.CommonConverter;
import com.bestcem.xm.user.grpc.service.converter.UserConditionConvert;
import com.bestcem.xm.user.grpc.service.converter.UserRoleConverter;
import com.bestcem.xm.user.grpc.service.converter.UserUserConverter;
import com.bestcem.xm.user.grpc.service.param.GroupIdsPageParam;
import com.bestcem.xm.user.mq.send.biz.UserMessageSendService;
import com.bestcem.xm.user.service.*;
import com.bestcem.xm.user.service.dto.group.IdRelationDTO;
import com.bestcem.xm.user.service.dto.group.UserConditionGroupDTO;
import com.bestcem.xm.user.service.dto.group.UserGroupDTO;
import com.bestcem.xm.user.service.dto.user.*;
import com.bestcem.xm.user.util.business.PwdUtil;
import com.bestcem.xm.user.util.business.UserUtil;
import com.bestcem.xm.user.util.convert.UserConvert;
import com.google.protobuf.Empty;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户中心账号相关grpc服务
 *
 * @author panyun <yun.pan@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/8 15:29
 */
@Slf4j
@GrpcService
public class UserUserGrpcService extends UserServiceGrpc.UserServiceImplBase {

    @Resource
    private UserService userService;

    @Resource
    private UserUserRoleService userUserRoleService;

    @Resource
    private UserGroupService userGroupService;

    @Resource
    private UserUserGroupService userUserGroupService;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private SsoService ssoService;

    @Resource
    private UserConvert userConvert;

    @Resource
    private RoleService roleService;

    @Resource
    private UserUtil userUtil;

    //@Resource
    //private UserMessageSender userMessageSender;

    @Resource
    private UserMessageSendService userMessageSendService;

    /**
     * 更新User
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/8 18:15
     */
    @Override
    public void updateUser(UpdateUserRequest request, StreamObserver<UpdateUserResponse> responseObserver) {
        UpdateUserResponse.Builder builder = UpdateUserResponse.newBuilder();
        OperateUser operateUser = request.getUser();
        String id = request.getId();

        //参数校验
        if (!ObjectId.isValid(id)) {
            builder.setStatus(RpcStatusResult.error("id格式不正确"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        //grpc请求参数转换为本地入参
        UserDTO userDTO = UserUserConverter.operateUser2Dto(operateUser);
        userDTO.setUserId(id);

        //更新
        ServiceResult<UserDTO> updateResult = userService.updateUser(userDTO);

        //返回结果
        if (updateResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setId(id);
        } else {
            builder.setStatus(RpcStatusResult.error(updateResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 通过ids批量获取User
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/9 15:14
     */
    @Override
    public void listUsersByIds(ListUsersByIdsRequest request, StreamObserver<ListUsersByIdsResponse> responseObserver) {
        ListUsersByIdsResponse.Builder builder = ListUsersByIdsResponse.newBuilder();
        List<String> ids = request.getIdsList();

        //参数校验
        for (String userId : ids) {
            if (!ObjectId.isValid(userId)) {
                builder.setStatus(RpcStatusResult.error(String.format("id:%s 格式不正确", userId)));
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
                return;
            }
        }

        // userId对应roleIdList
        HashMap<String, List<String>> userUserRoleIdsMap = getRoleIdList(ids);

        ServiceResult<List<UserDTO>> serviceResult = userService.selectByIds(ids);

        //返回结果
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllUsers(UserUserConverter.userListToGrpc(serviceResult.getData(), userUserRoleIdsMap));
        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据userId获取用户详情
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/14 15:13
     */
    @Override
    public void getUserById(GetUserByIdRequest request, StreamObserver<GetUserByIdResponse> responseObserver) {
        GetUserByIdResponse.Builder builder = GetUserByIdResponse.newBuilder();
        List<String> ids = Collections.singletonList(request.getId());

        //参数校验
        if (!ObjectId.isValid(request.getId())) {
            builder.setStatus(RpcStatusResult.error(String.format("id:%s 格式不正确", request.getId())));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // userId对应roleIdList
        HashMap<String, List<String>> userUserRoleIdsMap = getRoleIdList(ids);

        ServiceResult<List<UserDTO>> serviceResult = userService.selectByIds(ids);
        List<User> users = UserUserConverter.userListToGrpc(serviceResult.getData(), userUserRoleIdsMap);

        //返回结果
        if (serviceResult.isSuccess() && !CollectionUtils.isEmpty(users)) {
            builder.setStatus(RpcStatusResult.success());
            builder.setUser(users.get(0));
        } else if (CollectionUtils.isEmpty(users)) {
            builder.setStatus(RpcStatusResult.error("未查询到用户信息"));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据 role_id 获取用户列表
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/9 17:01
     */
    @Override
    public void listUsersByRoleId(ListUsersByRoleIdRequest request, StreamObserver<ListUsersByRoleIdResponse> responseObserver) {
        ListUsersByRoleIdResponse.Builder builder = ListUsersByRoleIdResponse.newBuilder();
        String roleId = request.getRoleId();
        String groupId = request.getGroupId();
        String levelId = request.getLevelId();

        //参数校验
        List<String> violationMessages = validateSelectiveParam(roleId, groupId, levelId);
        if (CollUtil.isNotEmpty(violationMessages)) {
            builder.setStatus(RpcStatusResult.error(violationMessages.get(0)));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 获取groupIdList
        List<String> groupIdList = new ArrayList<>();
        if (StringUtils.isBlank(groupId) && StringUtils.isNotBlank(levelId)) {
            UserGroupDTO userGroupDTO = new UserGroupDTO();
            userGroupDTO.setGroupLevelId(levelId);
            ServiceResult<List<UserGroupDTO>> groupListResult = userGroupService.listBySelective(userGroupDTO);
            //去重
            groupIdList = groupListResult.getData().stream().map(UserGroupDTO::getGroupId).distinct().collect(Collectors.toList());
        } else if (StringUtils.isNotBlank(groupId) && StringUtils.isNotBlank(levelId)) {
            ServiceResult<UserGroupDTO> groupService = userGroupService.getById(groupId);
            if (groupService.isSuccess()) {
                ServiceResult<List<String>> groupIdService = userGroupService.getGroupAncestorsByGroupId(groupService.getData().getGroupId());
                List<String> groupIds = groupIdService.getData();
                groupIds.add(groupService.getData().getGroupId());

                ServiceResult<List<UserGroupDTO>> groupList = userGroupService.listByLevelIdAndGroupIds(levelId, groupIds);
                if (!groupList.isSuccess() || CollectionUtils.isEmpty(groupList.getData())) {
                    builder.setStatus(RpcStatusResult.error(groupList.getMsg()));
                    builder.addAllUsers(new ArrayList<>());
                    responseObserver.onNext(builder.build());
                    responseObserver.onCompleted();
                    return;
                }
                groupIdList = Collections.singletonList(groupList.getData().get(0).getGroupId());
            }
        } else {
            groupIdList = Collections.singletonList(groupId);
        }

        // 获取userList
        List<UserDTO> userList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(groupIdList)) {
            GroupIdsPageParam param = new GroupIdsPageParam();
            param.setGroupIds(groupIdList);
            ServiceResult<List<String>> userIdsFromGroups = userUserGroupService.listUserFromGroups(param);
            if (CollectionUtils.isNotEmpty(userIdsFromGroups.getData())) {
                userList = getUserListByRole(roleId, userIdsFromGroups.getData(), null);
            }
        } else if (StringUtils.isNotBlank(roleId)) {
            userList = getUserListByRole(roleId, Lists.newArrayList(), null);
        } else {
            userList = Lists.newArrayList();
        }

        if (CollectionUtils.isEmpty(userList)) {
            builder.setStatus(RpcStatusResult.success());
            builder.setTotal(0);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // userIdList获取对应的RoleIdList
        List<String> userIdList = userList.stream().map(UserDTO::getUserId).collect(Collectors.toList());
        int size = userIdList.size();
        HashMap<String, List<String>> roleIdListMap = getRoleIdList(userIdList);

        //返回结果
        builder.setStatus(RpcStatusResult.success());
        builder.setTotal(size);
        builder.addAllUsers(UserUserConverter.userListToGrpc(userList, roleIdListMap));
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * copy_sample 复制旧公司
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/9 17:01
     */
    @Override
    public void listUserIdMaps(ListUserIdMapsRequest request, StreamObserver<ListUserIdMapsResponse> responseObserver) {
        ListUserIdMapsResponse.Builder builder = ListUserIdMapsResponse.newBuilder();
        String srcOrgId = request.getSrcOrgId();
        String dstOrgId = request.getDstOrgId();

        //参数校验
        ArrayList<String> errmsgList = new ArrayList<>();
        if (!ObjectId.isValid(srcOrgId)) {
            errmsgList.add("srcOrgId格式不正确");
        }
        if (!ObjectId.isValid(dstOrgId)) {
            errmsgList.add("dstOrgId格式不正确");
        }
        if (!CollectionUtils.isEmpty(errmsgList)) {
            builder.setStatus(RpcStatusResult.error(errmsgList.get(0)));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 获取源公司和新公司的系统管理员角色ID，一个公司只有一个系统管理员角色
        ServiceResult<String> dstAdmin = roleService.getAdminRole(dstOrgId);
        if (!dstAdmin.isSuccess()) {
            builder.setStatus(RpcStatusResult.error("获取系统管理员角色失败"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        String dstAdminRoleId = dstAdmin.getData();

        // 获取新公司所有管理员userId
        ServiceResult<List<String>> result = userService.listByRoleIdJoinUserRole(dstOrgId, dstAdminRoleId);
        List<String> userIds = result.getData();

        ArrayList<IdRelationDTO> idRelationList = new ArrayList<>();
        if (CollectionUtils.isEmpty(userIds)) {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllIdRelations(new ArrayList<>());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        } else {
            String dstAdminId = userIds.get(0);

            // 将源公司所有用户都映射为新公司的系统管理员
            UserDTO userDTO = new UserDTO();
            userDTO.setOrgId(srcOrgId);
            ServiceResult<List<UserDTO>> listServiceResult = userService.listByCondition(userDTO);

            for (UserDTO dto : listServiceResult.getData()) {
                IdRelationDTO idRelationDTO = IdRelationDTO.builder()
                        .oldId(dto.getUserId())
                        .newId(dstAdminId)
                        .build();
                idRelationList.add(idRelationDTO);
            }
        }
        builder.setStatus(RpcStatusResult.success());
        builder.addAllIdRelations(CommonConverter.idRelationDtosGrpcs(idRelationList));
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取每个userId对应roleIdList
     *
     * @param userIdList
     * @return java.util.HashMap<java.lang.String, java.util.List < java.lang.String>>
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/10 14:54
     */
    private HashMap<String, List<String>> getRoleIdList(List<String> userIdList) {
        HashMap<String, List<String>> userUserRoleIdsMap = new HashMap<>(16);
        for (String userId : userIdList) {
            UserUserRoleDTO userUserRoleDTO = new UserUserRoleDTO();
            userUserRoleDTO.setUserId(userId);
            ServiceResult<List<UserUserRoleDTO>> roleListResult = userUserRoleService.listByCondition(userUserRoleDTO);
            if (roleListResult.isSuccess()) {
                List<String> roleIdList = roleListResult.getData().stream().map(UserUserRoleDTO::getRoleId).collect(Collectors.toList());
                userUserRoleIdsMap.put(userId, roleIdList);
            }
        }

        return userUserRoleIdsMap;
    }

    /**
     * 筛选对应角色的有效用户
     * XM.apps_mysql.user.util.utils.get_user_list_by_role
     *
     * @param roleId
     * @param userIds
     * @param limit
     * @return java.util.List<com.bestcem.xm.user.service.dto.user.UserDTO>
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/10 11:03
     */
    private List<UserDTO> getUserListByRole(String roleId, List<String> userIds, Integer limit) {
        if (StringUtils.isBlank(roleId) && CollectionUtils.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        if (Objects.isNull(limit)) {
            limit = 10000;
        }
        Integer status = UserStatusEnum.ACTIVATED.getStatus();
        ServiceResult<List<UserDO>> listByIds = userService.listByIds(roleId, status, userIds, limit);

        return userConvert.dos2Dtos(listByIds.getData());
    }

    /**
     * 参数校验
     *
     * @param roleId
     * @param groupId
     * @param levelId
     * @return java.util.List<java.lang.String>
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/10 11:24
     */
    private List<String> validateSelectiveParam(String roleId, String groupId, String levelId) {
        ArrayList<String> violationMessages = new ArrayList<>();
        if (StringUtils.isBlank(roleId)) {
            violationMessages.add("roleId为必传参数");
        }
        if (StringUtils.isNotBlank(roleId) && !ObjectId.isValid(roleId)) {
            violationMessages.add("roleId格式不正确");
        }
        if (StringUtils.isNotBlank(groupId) && !ObjectId.isValid(groupId)) {
            violationMessages.add("groupId格式不正确");
        }
        if (StringUtils.isNotBlank(levelId) && !ObjectId.isValid(levelId)) {
            violationMessages.add("levelId格式不正确");
        }
        return violationMessages;
    }

    /**
     * 创建sso用户
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/31 1:37
     */
    @Override
    public void createUserBySso(CreateUserBySsoRequest request,
                                StreamObserver<CreateUserBySsoResponse> responseObserver) {
        CreateUserBySsoResponse.Builder builder = CreateUserBySsoResponse.newBuilder();
        OperateUser user = request.getUser();

        if (StringUtils.isBlank(user.getOrgId()) && !ObjectId.isValid(user.getOrgId())) {
            builder.setStatus(RpcStatusResult.error("orgId为空或者格式不正确"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 校验参数是否存在
        UserDTO userDTO = UserUserConverter.operateUser2Dto(user);
        boolean innerUser = userUtil.checkUserIsInner(userDTO.getPhone(), userDTO.getEmail(), "");
        userDTO.setInnerFlag(BooleanStatusEnum.toInteger(innerUser));
        ServiceResult<List<UserDO>> serviceResult = userService.selectByOrgIdSelective(userDTO);
        if (!CollectionUtils.isEmpty(serviceResult.getData())) {
            builder.setStatus(RpcStatusResult.error("用户信息已存在，请检查您的参数"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<String> result = ssoService.createUser(userDTO, new ArrayList<>(), null, new ArrayList<>(), false);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        builder.setStatus(RpcStatusResult.success());
        builder.setId(result.getData());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 新增用户（定制）
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/6/30 14:11
     */
    @Override
    public void createUser(CreateUserRequest request,
                           StreamObserver<CreateUserResponse> responseObserver) {
        CreateUserResponse.Builder builder = CreateUserResponse.newBuilder();
        OperateUser user = request.getUser();
        String rootGroupId = request.getRootGroupId();
        List<String> groupIdList = request.getGroupIdsList();
        Boolean checkParams = request.getCheckParams();

        if (StringUtils.isBlank(user.getOrgId()) && !ObjectId.isValid(user.getOrgId())) {
            builder.setStatus(RpcStatusResult.error("orgId为空或者格式不正确"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 校验参数是否存在
        UserDTO userDTO = UserUserConverter.operateUser2Dto(user);
        boolean innerUser = userUtil.checkUserIsInner(userDTO.getPhone(), userDTO.getEmail(), "");
        userDTO.setInnerFlag(BooleanStatusEnum.toInteger(innerUser));
        ServiceResult<List<UserDO>> serviceResult = userService.selectByOrgIdSelective(userDTO);
        if (!CollectionUtils.isEmpty(serviceResult.getData())) {
            builder.setStatus(RpcStatusResult.error("用户信息已存在，请检查您的参数"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<String> result = ssoService.createUser(userDTO, user.getRoleIdsList(), rootGroupId, groupIdList, checkParams);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        builder.setStatus(RpcStatusResult.success());
        builder.setId(result.getData());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    /**
     * 通过条件灵活筛选返回user,仅获得一个用户 (齐正国|定制)
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/31 2:01
     */
    @Override
    public void getUserByFilter(GetUserByFilterRequest request,
                                StreamObserver<GetUserByFilterResponse> responseObserver) {
        GetUserByFilterResponse.Builder builder = GetUserByFilterResponse.newBuilder();
        UserCondition userCondition = request.getUser();
        String orgId = userCondition.getOrgId();
        if (!ObjectId.isValid(orgId)) {
            builder.setStatus(RpcStatusResult.error("orgId格式不正确"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // grpc请求参数转换为本地入参
        UserDTO userDTO = UserUserConverter.userCondition2Dto(userCondition);

        if (Objects.isNull(userDTO.getStatus())) {
            userDTO.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        }

        // 查询
        ServiceResult<UserDTO> result = userService.getOneUserByFilter(userDTO);
        if (result.isSuccess() && Objects.nonNull(result.getData())) {
            UserDTO user = result.getData();

            // userId对应roleIdList
            HashMap<String, List<String>> userUserRoleIdsMap = getRoleIdList(Collections.singletonList(user.getUserId()));

            builder.setStatus(RpcStatusResult.success())
                    .setUser(UserUserConverter.userListToGrpc(Collections.singletonList(user), userUserRoleIdsMap).get(0));
        } else {
            builder.setStatus(RpcStatusResult.error("找不到相关用户"));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 通过条件灵活筛选返回user列表
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/6/30 14:03
     */
    @Override
    public void listUsersByFilter(ListUsersByFilterRequest request,
                                  StreamObserver<ListUsersByFilterResponse> responseObserver) {
        ListUsersByFilterResponse.Builder builder = ListUsersByFilterResponse.newBuilder();
        UserCondition userCondition = request.getUser();
        String orgId = userCondition.getOrgId();
        if (!ObjectId.isValid(orgId)) {
            builder.setStatus(RpcStatusResult.error("orgId格式不正确"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // grpc请求参数转换为本地入参
        UserDTO userDTO = UserUserConverter.userCondition2Dto(userCondition);

        if (Objects.isNull(userDTO.getStatus())) {
            userDTO.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        }

        // 查询
        ServiceResult<List<UserDTO>> result = userService.getUserByCondition(userDTO);
        if (result.isSuccess() && Objects.nonNull(result.getData())) {
            List<UserDTO> users = result.getData();
            List<String> userIds = users.stream().map(UserDTO::getUserId).collect(Collectors.toList());

            // userId对应roleIdList
            HashMap<String, List<String>> userUserRoleIdsMap = getRoleIdList(userIds);

            builder.setStatus(RpcStatusResult.success())
                    .addAllUsers(UserUserConverter.userListToGrpc(users, userUserRoleIdsMap));
        } else {
            builder.setStatus(RpcStatusResult.error("找不到相关用户"));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getAuditor(GetAuditRequest request, StreamObserver<GetAuditResponse> responseObserver) {
        GetAuditResponse.Builder builder = GetAuditResponse.newBuilder();

        // 根据org_id和user_id判断用户是否拥有审核者的权限
        String orgId = request.getOrgId();
        log.info("Now the getAuditor, orgId = {}", orgId);
        // 获取系统内置的投放审核角色
        List<CheckUserInfo> checkUserInfos =  new ArrayList<>();
        ServiceResult<String> deliverCheckRole = roleService.getDeliverCheckRole(orgId);
        if (deliverCheckRole.isSuccess() && StringUtils.isNotBlank(deliverCheckRole.getData())) {
            String roleId = deliverCheckRole.getData();
            List<String> userIds = userUserRoleService.listUserIdsByRoleId(roleId).getData();
            if (CollectionUtils.isNotEmpty(userIds)) {
                // 根据userIds查询用户信息列表
                ServiceResult<List<UserDTO>> users = userService.selectByIds(userIds);
                List<UserDTO> data = Optional.ofNullable(users.getData()).orElse(new ArrayList<>());
                log.info("Now the checkUsers = {}", data);
                for (UserDTO user : data) {
                    checkUserInfos.add(CheckUserInfo.newBuilder().setName(user.getName())
                        .setUsername(user.getUserName()).setMobile(user.getUserName())
                        .setEmail(user.getEmail()).setStaus(user.getStatus()).setId(user.getUserId())
                        .setOrgId(user.getOrgId()).build());
                }
            }
        }
        builder.setStatus(RpcStatusResult.success());
        builder.addAllCheckUsers(checkUserInfos);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据org_id和user_id判断用户是否拥有审核者权限
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/03/14 11:57
     */
    @Override
    public void checkAuditor(CheckAuditRequest request, StreamObserver<CheckAuditResponse> responseObserver) {
        // 获取返回对象的构造器
        CheckAuditResponse.Builder builder = CheckAuditResponse.newBuilder();

        // 根据org_id和user_id判断用户是否拥有审核者的权限
        ServiceResult<Boolean> result = userService.checkReviewer(request.getOrgId(), request.getUserId());
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            builder.setValid(result.getData());
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据org_id和user_id判断用户是否拥有审核者权限
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 16:47
     */
    @Override
    public void checkAuditorPermission(CheckAuditorPermissionRequest request, StreamObserver<CheckAuditorPermissionResponse> responseObserver) {
        // 获取返回对象的构造器
        CheckAuditorPermissionResponse.Builder builder = CheckAuditorPermissionResponse.newBuilder();

        // 根据org_id和user_id判断用户是否拥有审核者的权限
        ServiceResult<Boolean> result = userService.checkReviewerPerm(request.getOrgId(), request.getUserId());
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setAuditor(result.getData());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 查询用户拥有的权限列表
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/03/14 11:57
     */
    @Override
    public void listUserPermissions(ListUserPermissionsRequest request, StreamObserver<ListUserPermissionsResponse> responseObserver) {
        // 获取返回对象的构造器
        ListUserPermissionsResponse.Builder builder = ListUserPermissionsResponse.newBuilder();

        // 根据user_id查询permissions列表
        ServiceResult<List<String>> result = userService.listUserPermissions(request.getUserId());
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllPermissions(result.getData());
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 校验用户是否是系统管理员
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/3/14 15:50
     */
    @Override
    public void checkSuper(CheckSuperRequest request, StreamObserver<CheckSuperResponse> responseObserver) {
        // 获取返回对象的构造器
        CheckSuperResponse.Builder builder = CheckSuperResponse.newBuilder();

        // 判断用户是否是系统管理员
        ServiceResult<Integer> result = userBusinessService.checkSuper(request.getUserId(), null);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            builder.setSuper(NumberUtils.INTEGER_ONE.equals(result.getData()));
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 校验是否是内部用户
     *
     * @param request
     * @param responseObserver
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/06/16 16:39
     */
    @Override
    public void checkInner(CheckInnerRequest request, StreamObserver<CheckInnerResponse> responseObserver) {
        // 获取返回对象的构造器
        CheckInnerResponse.Builder builder = CheckInnerResponse.newBuilder();

        // 判断用户是否是内部用户
        boolean checkInnerUserResult = userUtil.checkUserIsInner(request.getPhone(), request.getEmail(), "");
        builder.setStatus(RpcStatusResult.success());
        builder.setInner(checkInnerUserResult);

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listUsersByGroupLevelIdAndRoleId(ListUsersByGroupLevelIdAndRoleIdRequest request, StreamObserver<ListUsersByGroupLevelIdAndRoleIdResponse> responseObserver) {
        List<UserConditionLevel> conditionsList = request.getConditionsList();
        String orgId = request.getOrgId();
        List<UserDO> users = userService.listUsersByGroupLevelAndRoleId(conditionsList, orgId);
        List<TicketUserInfo> ticketUserList = users.stream().map(user -> {
            TicketUserInfo.Builder builder = TicketUserInfo.newBuilder()
                    .setId(user.getUserId())
                    .setOrgId(user.getOrgId())
                    .setUsername(user.getUserName())
                    .setName(user.getName());
            if (user.getAvatar() != null) {
                builder.setAvatar(user.getAvatar());
            }
            if (user.getEmail() != null) {
                builder.setEmail(user.getEmail());
            }
            if (user.getPhone() != null) {
                builder.setPhone(user.getPhone());
            }
            return builder.build();
        }).collect(Collectors.toList());

        ListUsersByGroupLevelIdAndRoleIdResponse.Builder builder = ListUsersByGroupLevelIdAndRoleIdResponse.newBuilder();
        builder.setStatus(RpcStatusResult.success());
        builder.addAllUsers(ticketUserList);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据用户组织和角色获取用户
     *
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/7/6 13:51
     */
    @Override
    public void listUsersByGroupIdAndRoleId(ListUsersByGroupIdAndRoleIdRequest request, StreamObserver<ListUsersByGroupIdAndRoleIdResponse> responseObserver) {
        ListUsersByGroupIdAndRoleIdResponse.Builder builder = ListUsersByGroupIdAndRoleIdResponse.newBuilder();
        String orgId = request.getOrgId();
        if (!ObjectId.isValid(orgId)) {
            builder.setStatus(RpcStatusResult.error("orgId格式不正确"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        List<UserConditionGroup> conditions = request.getConditionsList();
        if (CollectionUtils.isEmpty(conditions)) {
            builder.setStatus(RpcStatusResult.success());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        List<UserConditionGroupDTO> conditionDtoList = new ArrayList<>();
        for (UserConditionGroup condition : conditions) {
            if (ObjectId.isValid(condition.getGroupId()) && ObjectId.isValid(condition.getRoleId())) {
                conditionDtoList.add(new UserConditionGroupDTO(condition.getGroupId(), condition.getRoleId()));
            }
        }
        ServiceResult<List<UserDTO>> serviceResult = userBusinessService.listUsersByGroupIdAndRoleId(conditionDtoList);
        if (!serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            List<UserDTO> userDtoList = serviceResult.getData();
            List<UserInfo> userInfoList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(userDtoList)) {
                for (UserDTO userDto : userDtoList) {
                    userInfoList.add(UserUserConverter.userDtoToUserInfo(userDto));
                }
            }
            builder.addAllUsers(userInfoList);
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 开放平台创建用户
     * user_openplatform_create_user
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/03/14 14:52
     */
    @Override
    public void createOpenUser(CreateOpenUserRequest request, StreamObserver<CreateOpenUserResponse> responseObserver) {

        CreateOpenUserResponse.Builder builder = CreateOpenUserResponse.newBuilder();
        //grpc请求参数转换为本地入参
        UserDTO userDTO = UserUserConverter.openUser2UserDTO(request.getUser());


        if (StringUtils.isBlank(userDTO.getSilentId())) {
            builder.setStatus(RpcStatusResult.error("silentId is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        if (StringUtils.isBlank(userDTO.getUserName())) {
            builder.setStatus(RpcStatusResult.error("userName is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (userDTO.getUserName().length() > BusinessConstant.USERNAME_MAX_LENGTH) {
            builder.setStatus(RpcStatusResult.error("userName is too long"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (StringUtils.isNotBlank(userDTO.getName()) && userDTO.getName().length() > BusinessConstant.USERNAME_MAX_LENGTH) {
            builder.setStatus(RpcStatusResult.error("name is too long"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (StringUtils.isNotBlank(userDTO.getContent()) && userDTO.getContent().length() > BusinessConstant.USERNAME_MAX_LENGTH) {
            builder.setStatus(RpcStatusResult.error("content is too long"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (userDTO.getUserName().contains("@")) {
            builder.setStatus(RpcStatusResult.error("userName must not contain \"@\""));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        if (StringUtils.isBlank(userDTO.getEmail())) {
            builder.setStatus(RpcStatusResult.error("email is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (CollectionUtils.isEmpty(request.getGroupIdsList()) || CollectionUtils.isEmpty(request.getRoleIdsList())) {
            builder.setStatus(RpcStatusResult.error("group or role is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        String orgCode = request.getOrgCode();
        ServiceResult<OrganizationDTO> organizationResult = organizationService.selectByOrgCode(orgCode);
        if (!organizationResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(organizationResult.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        OrganizationDTO organizationDTO = organizationResult.getData();
        String orgId = organizationDTO.getOrgId();
        List<UserDTO> userListByUserName = userService.getUserListByUsernameOrEmailOrPhone(orgId, userDTO.getUserName(), null, null);
        if (CollectionUtils.isNotEmpty(userListByUserName)) {
            builder.setStatus(RpcStatusResult.error("username is Found"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (StringUtils.isNotBlank(userDTO.getPhone())) {
            Boolean phoneExist = userService.checkUserByEmailAndPhone(orgId, userDTO.getPhone(), null, null);
            if (Boolean.TRUE.equals(phoneExist)) {
                builder.setStatus(RpcStatusResult.error("mobile is Found"));
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
                return;
            }
        }
        if (StringUtils.isNotBlank(userDTO.getEmail())) {
            Boolean emailExist = userService.checkUserByEmailAndPhone(orgId, null, userDTO.getEmail(), null);
            if (Boolean.TRUE.equals(emailExist)) {
                builder.setStatus(RpcStatusResult.error("email is Found"));
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
                return;
            }
        }
        // 开放平台创建账号时检查 第三方id在我们系统中是否已存在
        Boolean silentIdExist = userService.checkUserBySilentId(orgId, userDTO.getSilentId());
        if (Boolean.TRUE.equals(silentIdExist)) {
            builder.setStatus(RpcStatusResult.error("该id对应账号已存在"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        // 检验租户配额
        ServiceResult<Boolean> result = userService.checkUserQuota(orgId, 1);
        // 用户数已达上限
        if (!Boolean.TRUE.equals(result.getData())) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        List<String> groupIds = request.getGroupIdsList();

        List<String> roleIds = request.getRoleIdsList();
        // 保存账号
        userDTO.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        String userId = userService.saveUser(orgId, userDTO, groupIds, roleIds);
        // MQ消息
        userMessageSendService.publishUserCreate(userDTO.getUserId(), groupIds);
        // 更新租户消费额
        userService.updateUserConsumption(orgId, 1);
        builder.setId(userId);
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    /**
     * 开放平台更新用户
     * user_openplatform_update_user
     *
     * @param request          请求信息
     * @param responseObserver 响应结果
     * @return void
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/03/14 14:52
     */
    @Override
    public void updateOpenUser(UpdateOpenUserRequest request, StreamObserver<UpdateOpenUserResponse> responseObserver) {
        UpdateOpenUserResponse.Builder builder = UpdateOpenUserResponse.newBuilder();
        //grpc请求参数转换为本地入参
        UserDTO userDTO = UserUserConverter.openUser2UserDTO(request.getUser());

        if (StringUtils.isBlank(userDTO.getSilentId())) {
            builder.setStatus(RpcStatusResult.error("silentId is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        if (StringUtils.isBlank(userDTO.getUserName())) {
            builder.setStatus(RpcStatusResult.error("userName is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (userDTO.getUserName().length() > BusinessConstant.USERNAME_MAX_LENGTH) {
            builder.setStatus(RpcStatusResult.error("userName is too long"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (StringUtils.isNotBlank(userDTO.getName()) && userDTO.getName().length() > BusinessConstant.USERNAME_MAX_LENGTH) {
            builder.setStatus(RpcStatusResult.error("name is too long"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (userDTO.getUserName().contains("@")) {
            builder.setStatus(RpcStatusResult.error("userName must not contain \"@\""));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        if (StringUtils.isBlank(userDTO.getEmail())) {
            builder.setStatus(RpcStatusResult.error("email is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (CollectionUtils.isEmpty(request.getGroupIdsList()) || CollectionUtils.isEmpty(request.getRoleIdsList())) {
            builder.setStatus(RpcStatusResult.error("group or role is required"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        if (StringUtils.isNotBlank(userDTO.getContent()) && userDTO.getContent().length() > BusinessConstant.USERNAME_MAX_LENGTH) {
            builder.setStatus(RpcStatusResult.error("content is too long"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        String orgCode = request.getOrgCode();
        List<String> groupIds = request.getGroupIdsList();
        List<String> roleIds = request.getRoleIdsList();

        ServiceResult<OrganizationDTO> organizationResult = organizationService.selectByOrgCode(orgCode);
        if (!organizationResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(organizationResult.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        OrganizationDTO organizationDTO = organizationResult.getData();
        String orgId = organizationDTO.getOrgId();

        UserDTO userCheck = new UserDTO();
        userCheck.setOrgId(orgId);
        if (StringUtils.isNotBlank(userDTO.getUserId())) {
            userCheck.setUserId(userDTO.getUserId());
        } else {
            userCheck.setSilentId(userDTO.getSilentId());
        }
        ServiceResult<List<UserDTO>> userExist = userService.selectList(userCheck);

        if (!userExist.isSuccess() || CollectionUtils.isEmpty(userExist.getData())) {
            builder.setStatus(RpcStatusResult.error("该用户不存在"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        UserDTO user = userExist.getData().get(0);

        if (StringUtils.isNotBlank(userDTO.getPhone())) {
            UserDTO check = new UserDTO();
            check.setOrgId(userDTO.getOrgId());
            check.setPhone(userDTO.getPhone());
            List<UserDTO> userDTOList = userService.getUserListByUsernameOrEmailOrPhone(userDTO.getOrgId(), userDTO.getUserName(), null, null);
            if (CollectionUtils.isNotEmpty(userDTOList) && StringUtils.isNotBlank(userDTOList.get(0).getSilentId())) {
                UserDTO userNameDTO = userDTOList.get(0);
                if (!userNameDTO.getSilentId().equals(userDTO.getSilentId())) {
                    builder.setStatus(RpcStatusResult.error("username is Found"));
                    responseObserver.onNext(builder.build());
                    responseObserver.onCompleted();
                    return;
                }
            }
        }

        if (StringUtils.isNotBlank(userDTO.getPhone())) {
            UserDTO check = new UserDTO();
            check.setOrgId(userDTO.getOrgId());
            check.setPhone(userDTO.getPhone());
            ServiceResult<List<UserDTO>> phoneResult = userService.selectList(check);
            if (CollectionUtils.isNotEmpty(phoneResult.getData()) && StringUtils.isNotBlank(phoneResult.getData().get(0).getSilentId())) {
                UserDTO phoneUser = phoneResult.getData().get(0);
                if (!phoneUser.getSilentId().equals(userDTO.getSilentId())) {
                    builder.setStatus(RpcStatusResult.error("mobile is Found"));
                    responseObserver.onNext(builder.build());
                    responseObserver.onCompleted();
                    return;
                }
            }
        }

        if (StringUtils.isNotBlank(userDTO.getEmail())) {
            UserDTO check = new UserDTO();
            check.setOrgId(userDTO.getOrgId());
            check.setEmail(userDTO.getEmail());
            ServiceResult<List<UserDTO>> emailResult = userService.selectList(check);
            if (CollectionUtils.isNotEmpty(emailResult.getData()) && StringUtils.isNotBlank(emailResult.getData().get(0).getSilentId())) {
                UserDTO emailUser = emailResult.getData().get(0);
                if (!emailUser.getSilentId().equals(userDTO.getSilentId())) {
                    builder.setStatus(RpcStatusResult.error("email is Found"));
                    responseObserver.onNext(builder.build());
                    responseObserver.onCompleted();
                    return;
                }
            }
        }

        UserUserConverter.openUserDTO2UserDTO(userDTO, user);

        // 更新组织
        userUserGroupService.updateUserGroups(orgId, user.getUserId(), groupIds);

        // 查询系统管理员
        ServiceResult<String> adminRoleResult = roleService.getAdminRole(orgId);
        String roleAdminId = adminRoleResult.getData();

        // 查询用户当前的角色id
        UserUserRoleDTO userUserRoleDTO = new UserUserRoleDTO();
        userUserRoleDTO.setUserId(user.getUserId());
        ServiceResult<List<UserUserRoleDTO>> roleIdsService = userUserRoleService.listByCondition(userUserRoleDTO);
        List<String> oldRoleIdList = roleIdsService.getData().stream().map(UserUserRoleDTO::getRoleId).collect(Collectors.toList());

        // 如果是给当前系统管理员添加角色，需要把他从oldRoleIdList移除，避免被后续的操作删除
        if (CollectionUtils.isNotEmpty(oldRoleIdList) && oldRoleIdList.contains(roleAdminId)) {
            oldRoleIdList.remove(roleAdminId);
        }

        // 检查用户的角色是否变化，如果变化则更新用户角色表
        userUserRoleService.checkUserRoleChangeAndUpdate(orgId, user.getUserId(), roleIds, oldRoleIdList, null);

        ServiceResult<Integer> result = userBusinessService.updateUser(user, true);
        if (result.isSuccess()) {
            builder.setId(user.getUserId());
            builder.setStatus(RpcStatusResult.success());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.setStatus(RpcStatusResult.error(result.getMsg()));
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    /**
     * 查询用户与角色的关联信息
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/3/30 11:21
     */
    @Override
    public void listUserRoles(ListUserRolesRequest request, StreamObserver<ListUserRolesResponse> responseObserver) {
        // 获取返回对象的构造器
        ListUserRolesResponse.Builder builder = ListUserRolesResponse.newBuilder();

        // 查询
        ServiceResult<List<UserUserRoleDTO>> result = userUserRoleService.listByCondition(UserRoleConverter.listUserRoleReq2Dto(request));
        // 设置返回值
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            if (CollectionUtils.isNotEmpty(result.getData())) {
                builder.addAllRoles(UserRoleConverter.userRoleDtos2Grpcs(result.getData()));
            }
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取角色为系统管理员的用户
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/3/30 11:22
     */
    @Override
    public void listAdmins(ListAdminsRequest request, StreamObserver<ListAdminsResponse> responseObserver) {
        // 获取返回对象的构造器
        ListAdminsResponse.Builder builder = ListAdminsResponse.newBuilder();

        // 查询公司系统管理员用户信息
        ServiceResult<UserDTO> result = userBusinessService.getAdminUserByOrgId(request.getOrgId());

        // 设置返回值
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            if (result.getData() != null) {
                builder.addUsers(NumberUtils.INTEGER_ZERO, UserUserConverter.userDto2Grpc(result.getData()));
            }
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取自动生成用户密码
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/3/30 11:23
     */
    @Override
    public void genPassword(Empty request, StreamObserver<GenPasswordResponse> responseObserver) {
        // 获取返回对象的构造器
        GenPasswordResponse.Builder builder = GenPasswordResponse.newBuilder();

        // 设置返回值
        builder.setStatus(RpcStatusResult.success());
        builder.setPassword(PwdUtil.genPassword());

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据搜索条件查询用户列表
     *
     * @param request          请求参数消息
     * @param responseObserver 返回值观察者
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 18:23 2022/6/28
     */
    @Override
    public void listUsers(ListUsersRequest request, StreamObserver<ListUsersResponse> responseObserver) {
        ListUsersResponse.Builder builder = ListUsersResponse.newBuilder();

        // 获取并转换参数
        UserConditionDTO userConditionDTO = UserConditionConvert.msg2Dto(request.getUser());
        String search = request.getSearch();
        List<String> fields = request.getFieldsList();
        List<Integer> statuses = request.getStatusesValueList();

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(userConditionDTO);

        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<List<UserDTO>> result = userService.listUsers(userConditionDTO, statuses, search, fields);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        List<User> users = result.getData().stream().map(UserUserConverter::dto2Msg).collect(Collectors.toList());
        builder.addAllUsers(users);
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取角色为系统管理员的用户请求，返回系统管理员列表
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/05/16 15:47
     */
    @Override
    public void listAdminsByOrgIds(ListAdminsByOrgIdsRequest request, StreamObserver<ListAdminsByOrgIdsResponse> responseObserver) {
        ListAdminsByOrgIdsResponse.Builder builder = ListAdminsByOrgIdsResponse.newBuilder();
        List<UserDTO> userDTOList = new ArrayList<>();
        List<String> orgIdList = request.getOrgIdsList();
        for (String orgId : orgIdList) {
            // 查询公司系统管理员用户信息
            ServiceResult<UserDTO> result = userBusinessService.getAdminUserByOrgId(orgId);
            userDTOList.add(result.getData());
        }
        builder.setStatus(RpcStatusResult.success());
        builder.addAllUsers(UserUserConverter.userDtos2Grpcs(userDTOList));
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void healthCheck(Empty request, StreamObserver<HealthCheckResponse> responseObserver) {
        HealthCheckResponse.Builder builder = HealthCheckResponse.newBuilder();
        builder.setStatus(RpcStatusResult.success());
        builder.setMsg("pong");
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取系统内置的投放审核用户
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 21:04
     */
    @Override
    public void listAuditors(ListAuditorsRequest request, StreamObserver<ListAuditorsResponse> responseObserver) {
        // 获取返回对象的构造器
        ListAuditorsResponse.Builder builder = ListAuditorsResponse.newBuilder();

        // 查询公司投放审核用户信息
        ServiceResult<List<UserDTO>> result = userBusinessService.getDeliverCheckUserByOrgId(request.getOrgId());

        // 设置返回值
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            if (CollectionUtils.isNotEmpty(result.getData())) {
                builder.addAllUsers(UserUserConverter.userDtos2Grpcs(result.getData()));
            }
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取系统管理员角色id列表
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 21:06
     */
    @Override
    public void listAdminIds(ListAdminIdsRequest request, StreamObserver<ListAdminIdsResponse> responseObserver) {
        // 获取返回对象的构造器
        ListAdminIdsResponse.Builder builder = ListAdminIdsResponse.newBuilder();

        // 查询公司系统管理员用户信息
        ServiceResult<UserDTO> result = userBusinessService.getAdminUserByOrgId(request.getOrgId());

        // 设置返回值
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            if (result.getData() != null) {
                builder.addIds(result.getData().getUserId());
            }
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取高级管理员id列表
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 21:09
     */
    @Override
    public void listSeniorAdminIds(ListSeniorAdminIdsRequest request, StreamObserver<ListSeniorAdminIdsResponse> responseObserver) {
        // 获取返回对象的构造器
        ListSeniorAdminIdsResponse.Builder builder = ListSeniorAdminIdsResponse.newBuilder();

        // 查询公司系统管理员用户信息
        ServiceResult<List<UserDTO>> result = userBusinessService.getSeniorAdminByOrgId(request.getOrgId());

        // 设置返回值
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            if (CollectionUtils.isNotEmpty(result.getData())) {
                Set<String> userIds = result.getData().stream().map(UserDTO::getUserId).collect(Collectors.toSet());
                builder.addAllIds(userIds);
            }
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * <pre>
     * 获取用户属性
     * &#64;Author wangyunyun &lt;yunyun.wang&#64;idiaoyan.com&gt;
     * </pre>
     */
    @Override
    public void getUserProperty(GetUserPropertyRequest request, StreamObserver<GetUserPropertyResponse> responseObserver) {
        // 获取返回对象的构造器
        GetUserPropertyResponse.Builder builder = GetUserPropertyResponse.newBuilder();
        // 设置参数
        UserDTO userDTO = new UserDTO();
        userDTO.setUserId(request.getId());
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setCode(request.getOrgCode());
        organizationDTO.setInnerFlag(request.getOrgInner() ? OrgInnerFlagEnum.INNER.getType() : OrgInnerFlagEnum.OUTTER.getType());
        // 获取用户属性
        ServiceResult<GrowingioDTO> result = userBusinessService.getUserProperty(userDTO, organizationDTO,
                StringUtils.isNotBlank(request.getPackageName()) ? request.getPackageName() : request.getPackageId());

        // 设置返回值
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setGrowingio(CommonConverter.growingioDto2Grpc(result.getData()));
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 检查密码格式
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 21:43
     */
    @Override
    public void checkPassword(CheckPasswordRequest request, StreamObserver<CheckPasswordResponse> responseObserver) {
        // 获取返回对象的构造器
        CheckPasswordResponse.Builder builder = CheckPasswordResponse.newBuilder();
        // 校验参数与处理业务
        ServiceResult<Boolean> result = handleCheckPassword(request);
        // 设置返回值
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setValid(result.getData());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 处理检查密码格式业务逻辑
     *
     * @param request
     * @return ServiceResult<Boolean>
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 21:47
     */
    private ServiceResult<Boolean> handleCheckPassword(CheckPasswordRequest request) {
        // 校验参数
        if (StringUtils.isBlank(request.getPassword())) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "password cannot be blank");
        }
        if (StringUtils.isBlank(request.getSalt())) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "salt cannot be blank");
        }
        if (StringUtils.isBlank(request.getPlainPassword())) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "plain_password cannot be blank");
        }
        // 校验并设置返回值
        return ServiceResult.success(PwdUtil.checkPassword(request.getPlainPassword(), request.getPassword(), request.getSalt()));
    }

    /**
     * 获取用户name
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 21:48
     */
    @Override
    public void getUserName(GetUserNameRequest request, StreamObserver<GetUserNameResponse> responseObserver) {
        // 获取返回对象的构造器
        GetUserNameResponse.Builder builder = GetUserNameResponse.newBuilder();
        ServiceResult<String> result = userBusinessService.getDisplayUserNameByUserId(request.getId());
        // 设置返回值
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setUserName(result.getData());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据用户名密码查询用户
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/30 11:37
     */
    @Override
    public void listUserByAuth(ListUserByAuthRequest request, StreamObserver<ListUserByAuthResponse> responseObserver) {
        // 获取返回对象的构造器
        ListUserByAuthResponse.Builder builder = ListUserByAuthResponse.newBuilder();
        ServiceResult<List<UserDTO>> result = userBusinessService.listUserByAuth(request.getUsername(), request.getPassword(), request.getOrgCode());
        // 设置返回值
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllUsers(UserUserConverter.userDtos2Grpcs(result.getData()));
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 套餐升级 修改show_guide字段
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/07/07 20:10
     */
    @Override
    public void updateShowGuideByOrgId(UpdateShowGuideByOrgIdRequest request, StreamObserver<UpdateShowGuideByOrgIdResponse> responseObserver) {

        // 获取返回对象的构造器
        UpdateShowGuideByOrgIdResponse.Builder builder = UpdateShowGuideByOrgIdResponse.newBuilder();

        String orgId = request.getOrgId();
        Integer showGuide = request.getShowGuide() ? BooleanStatusEnum.YES.getStatus() : BooleanStatusEnum.NO.getStatus();
        UserDTO userDTO = new UserDTO();
        userDTO.setOrgId(orgId);
        userDTO.setShowGuide(showGuide);
        ServiceResult<Integer> result = userService.updateByOrgIdSelective(userDTO);
        // 设置返回值
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void checkVcode(CheckVcodeRequest request, StreamObserver<CheckVcodeResponse> responseObserver) {
        CheckVcodeResponse.Builder builder = CheckVcodeResponse.newBuilder();
        if (StringUtils.isBlank(request.getPrefix()) || StringUtils.isBlank(request.getPhone()) || StringUtils.isBlank(request.getVcode())) {
            builder.setStatus(RpcStatusResult.error(ReqErrorCodeEnum.PARAM_LOST.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        ServiceResult<Boolean> result = userService.checkVcode(request.getPrefix(), request.getPhone(), request.getVcode());
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setSuccess(result.getData());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
